<?php
namespace app\agent\controller;

use app\agent\service\UserTginfoService;
use app\common\service\AddrService;
use think\Exception;

/**
 * 辖区经纪人管理
 * @module 辖区经纪人管理
 * @controller 辖区经纪人
 */
class UserTginfoController extends BaseController
{
	private $userTginfo = null;

	private $addr = null;

	private static $flag = [];
	private static $arr = [];
	private static $count = 0;

	public function __construct()
	{
		parent::__construct();
		
		$this->userTginfo = new UserTginfoService();
		
        $this->addr = new AddrService();
	}
	
	/**
	 * @action 辖区经纪人列表
	 */
	public function page()
	{
        $request              = input('param.');
        $request['type']      = session('type');
        $request['addr_code'] = session('addr_code');
		
		$data = $this->userTginfo->getViewPage($request);

        //获取下级下拉列表
        $addr[$this->getNowType($request['type'])] = $this->addr->getAddrByPcode($request['addr_code']);

        //下级下拉列表选择了则返回下下级下拉列表
        if( empty($request['city']) === false )
        {
            $addr['county'] = $this->addr->getAddrByPcode($request['city']);
        }
		$this->assign('request', $request);
		$this->assign('data', $data);
		$this->assign('addr', $addr);

		return $this->fetch('page');
	}
	
	
	/**
	 * @action 辖区经纪人详情
	 */
	public function detail()
	{
		$request = input('param.');
		
		$data = $this->userTginfo->getViewDetail($request);

		$this->assign('data', $data);
		
		return $this->fetch();
	}

    public function two()
    {
        $res = user_tginfo(6659, 1);

        dump($res);exit;
	}

    public function first()
    {
        ini_set('memory_limit','3072M');    // 临时设置最大内存占用为3G
        set_time_limit(0);   // 设置脚本最大执行时间 为0 永不过期

        echo date('Y-m-d H:i:s', time());
        //获取所有的经纪人
        $where = [
            ['status', '<>', -1],
            ['status', '<>', 0],
        ];
        self::$arr = db('user_tginfo')->field(['uid', 'bdtguid'])->where('status', 1)->where($where)->select();
        //对数据进行整理
        $array = [];
        foreach ( self::$arr as $key => $val)
        {
            $array[$val['uid']] = $val;
        }
        self::$arr = $array;
        unset($array);


        $pre = [
            'uid'       => 1,
            'bdtguid'   => 0,
            'structure' => [],
        ];
        self::$arr[$pre['uid']] = $pre;
        self::$flag[] = $pre['uid'];

        //遍历数据获取
        dump(date('Y-m-d H:i:s', time()));
        $this->eachTg(self::$arr, $pre);
        dump(date('Y-m-d H:i:s', time()));
        //对structure进行序列化
        foreach (self::$arr as $key => $val)
        {
            if( isset($val['structure']) )
            {
                self::$arr[$key]['structure'] = serialize($val['structure']);
            }
        }
        echo date('Y-m-d H:i:s', time());
        $res = dbSaveAll(self::$arr, 'bg_user_tginfo', 'uid');
        dump($res);
        echo date('Y-m-d H:i:s', time());
        exit;
    }

    /**
     * @param array $arr 所有数据
     * @param array $pre 上一级的数据
     */
	private function eachTg($arr = [], $pre = [])
    {
        foreach ( self::$arr as $key => $val)
        {
            self::$count++;
            if( $val['bdtguid'] === $pre['uid'] && in_array($val['uid'], self::$flag) === false )
            {
                //根据上级的结构链组装自己的结构链
                $structure                    = $pre['structure'];
                $structure[]                  = $pre['uid'];
                self::$arr[$key]['structure'] = $structure;

//                dump($pre);
                //根据结构链对所有上级的团队数量+1
                foreach ( self::$arr[$key]['structure'] as $k => $v )
                {
                    self::$count++;
                    //+1
                    self::$arr[$v] = addOne(self::$arr[$v]);
                }

                //标识自己已被查找
                self::$flag[] = $val['uid'];
//                dump(self::$flag);
//                dump('---------');

                //继续查找我的下级(递归)
                $this->eachTg(self::$arr, self::$arr[$key]);
            }
        }
    }

    /**
     * @action 经纪人审核通过
     */
    public function changeStatus()
    {
        $request = input('param.');

        if( $this->userTginfo->changeStatus($request) === false )
        {
            $this->failure('操作失败' . $this->userTginfo->getError());
        }

        $this->render('操作成功');
    }

    /**
     * 经纪人user表信息批量补充
     */
    public function addUserInfo()
    {
        $filed = [
            'tginfo.*',
        ];

        $join = [
            ['user', 'user.uid = tginfo.uid']
        ];

        $where = 'user.istuiguang <> tginfo.tgnumber AND user.bindtuiguang <> tginfo.bdtguid AND tginfo.status = 1';

        $data = db('user_tginfo')->alias('tginfo')->field($filed)->join($join)->where($where)->select();

        foreach ( $data as $key => $val )
        {
            $datas[] = [
                'istuiguang'   => $val['tgnumber'],
                'bindtuiguang' => $val['bdtguid'],
                'updatetime'   => time(),
                'uid'          => $val['uid'],
            ];
        }

        $res = dbSaveAll($datas, 'bg_user', 'uid');
        dump($res);exit;
    }
	
}

function addOne($array)
{
    if( empty($array['count']) )
    {
        $array['count'] = 1;
    }
    else
    {
        $array['count']++;
    }

    return $array;
}